package core;

import fileoperation.FileDeletion;
import gitobject.Commit;
import gitobject.GitObject;
import gitobject.Tree;
import repository.Repository;

import java.io.*;
import java.util.Arrays;

import fileoperation.FileCreation;
import fileoperation.FileDeletion;

public class JitBranch {
    public static String branchPath = Repository.getGitDir() + File.separator + "refs" + File.separator + "heads";
    public static String headFilePath = Repository.getGitDir() + File.separator + "HEAD";

    /**
     * Add files into your index.
     * @throws IOException
     */
    public static void printBranch() throws IOException {
        File branchDic = new File(branchPath); // 该目录下很多分支
        String[] branchNameLists = branchDic.list();
        String headContent = readFile(new File(headFilePath));  //HEAD里面的内容
        if(headContent != null) {
            String headPointer = headContent.substring(16).trim();  // 从ref: refs/heads/master第16位开始取,例如：master
            assert branchNameLists != null;
            for (String branchName : branchNameLists) {
                if (branchName.equals(headPointer)) System.out.println("* " + branchName);
                else System.out.println("  " + branchName);
            }
        }
    }

    /**
     * Add files into your index.
     * @param branchName
     * @throws IOException
     */
    public static void newBranch(String branchName) throws IOException {
        String[] branchList = new File(branchPath).list();
        assert branchList != null;
        if (!Arrays.asList(branchList).contains(branchName)){
            String headContent = readFile(new File(headFilePath));  //HEAD里面的内容
            if(headContent != null) {
                String headPointer = headContent.substring(16).trim();  // 从ref: refs/heads/master第16位开始取,例如：master
                String currentCommit = readFile(new File(branchPath + File.separator + headPointer));  //当前的指针
                if(currentCommit != null) {
                    FileCreation.createFile(branchPath, branchName, currentCommit);
                    System.out.println("create new branch '" + branchName + "'");
                }
            }
        }
        else {
            System.out.println("branch '" + branchName + "' already exists");
        }
    }

    /**
     * Add files into your index.
     * @param branchName
     */
    public static void deleteBranch(String branchName){
        File branchFile = new File(branchPath + File.separator + branchName);
        if (branchFile.exists() && branchFile.isFile()){
            FileDeletion.deleteFile(branchFile.getPath());
            System.out.println("delete branch '" + branchName + "'");
        }
        else {
            System.out.println("branch '" + branchName + "' does not exist");
        }

    }

    // 用来读取文件内容的函数
    public static String readFile(File path) throws IOException{
        if(path.exists()) {
            InputStream is = new FileInputStream(path);
            byte[] bytes = new byte[1024];
            int len = is.read(bytes);
            String str = "";
            while (len != -1) {
                str = new String(bytes, 0, len);
                len = is.read(bytes);
            }
            is.close();
            return str;
        }
        else{
            System.out.println("fatal: Not a valid object name: '" + path.getName() + "'.");
            return null;
        }
    }

    public static String getCommitId(String branchName) throws IOException{
        File branch = new File(branchPath + File.separator + branchName);
        if(branch.exists() && branch.isFile()){
            return readFile(branch);
        }
        else {
            System.out.printf("branch '%s' does not exist\r\n", branchName);
            return null;
        }
    }

    public static String getNowBranchName() throws IOException{
        File HEAD = new File(Repository.getGitDir() + File.separator + "HEAD");
        if(HEAD.exists()){
            String path = GitObject.getValue(HEAD);
            if(path.length() != 0)
                path = path.substring(5).trim();
            else return null;
            return new File(Repository.getGitDir() + File.separator + path.replace(Tree.treeSeparator, File.separator)).getName();
        }
        else return null;
    }

    public static boolean writeToBranch(String commitId, String branchName) throws IOException{
        File branchFile = new File(branchPath + File.separator + branchName);
        if(!branchFile.exists()){
            FileCreation.createFile(JitBranch.branchPath, JitBranch.getNowBranchName(), commitId);
            return true;
        }
        else {
            if (branchFile.isFile()) {
                FileWriter fw = new FileWriter(branchFile);
                fw.write(commitId);
                fw.flush();
                fw.close();
                return true;
            } else {
                System.out.println("fatal: branch '" + branchName + "' is a dictionary.");
                return false;
            }
        }
    }
}
